// 首页：搜索 + 列表 + 简易播放器 + 收藏/历史写入
const audio = wx.getBackgroundAudioManager()
const { toggleFav } = require('../../utils/util')
const { apiSongs, apiSearch, apiHistoryAdd, apiFavToggle } = require('../../utils/api')

Page({
  data: {
    keyword: '',
    posters: [
      { id: 1, url: 'https://images.unsplash.com/photo-1493225457124-a3eb161ffa5f?w=1200' },
      { id: 2, url: 'https://images.unsplash.com/photo-1511671782779-c97d3d27a1d4?w=1200' },
      { id: 3, url: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=1200' }
    ],
    songs: [
      { id: 1, name: '火', artist: '隔层', cover: 'https://picsum.photos/seed/1/100', url: 'https://www.kozco.com/tech/LRMonoPhase4.mp3' },
      { id: 2, name: '只因你太美', artist: '坤坤', cover: 'https://picsum.photos/seed/2/100', url: 'https://www.kozco.com/tech/piano2-CoolEdit.mp3' },
      { id: 3, name: '六六六', artist: '智子涵', cover: 'https://picsum.photos/seed/3/100', url: 'https://www.kozco.com/tech/organfinale.mp3' }
    ],
    current: {},
    playing: false,
    progress: 0
  },
  toggleFav(e){
    const id = e.currentTarget.dataset.id
    const song = this.data.songs.find(s=>s.id===id)
    if(!song){ return }
    const list = toggleFav(song)
    apiFavToggle({ id: song.id, name: song.name, artist: song.artist, cover: song.cover }).catch(()=>{})
    wx.showToast({ title: list.find(i=>i.id===id)? '已收藏' : '已取消', icon: 'none' })
  },
  onShow(){
    if(!wx.getStorageSync('token')){ wx.reLaunch({ url: '/pages/login/login' }) }
    this.bindAudioEvents()
    if(this.getTabBar && this.getTabBar()){
      this.getTabBar().updateActive()
    }
    // 使用本地歌曲数据
    apiSongs().then(list=>{ 
      if(Array.isArray(list) && list.length){ 
        this.setData({ songs: list }) 
      }
    })
  },
  onSearchInput(e){ this.setData({ keyword: e.detail.value }) },
  onSearch(){
    const kw = this.data.keyword.trim()
    if(!kw){ 
      // 如果搜索框为空，恢复原始推荐列表
      this.setData({ 
        songs: [
          { id: 1, name: '火', artist: '隔层', cover: 'https://picsum.photos/seed/1/100', url: 'https://www.kozco.com/tech/LRMonoPhase4.mp3' },
          { id: 2, name: '只因你太美', artist: '坤坤', cover: 'https://picsum.photos/seed/2/100', url: 'https://www.kozco.com/tech/piano2-CoolEdit.mp3' },
          { id: 3, name: '六六六', artist: '智子涵', cover: 'https://picsum.photos/seed/3/100', url: 'https://www.kozco.com/tech/organfinale.mp3' }
        ]
      })
      return 
    }
    // 先尝试本地搜索
    this.searchLocal(kw)
    // 然后尝试在线搜索
    this.searchOnline(kw)
  },
  searchLocal(keyword){
    // 本地搜索：在现有歌曲中查找
    const originalSongs = [
      { id: 1, name: '火', artist: '隔层', cover: 'https://picsum.photos/seed/1/100', url: 'https://www.kozco.com/tech/LRMonoPhase4.mp3' },
      { id: 2, name: '只因你太美', artist: '坤坤', cover: 'https://picsum.photos/seed/2/100', url: 'https://www.kozco.com/tech/piano2-CoolEdit.mp3' },
      { id: 3, name: '六六六', artist: '智子涵', cover: 'https://picsum.photos/seed/3/100', url: 'https://www.kozco.com/tech/organfinale.mp3' }
    ]
    const filtered = originalSongs.filter(song => 
      song.name.includes(keyword) || song.artist.includes(keyword)
    )
    if(filtered.length > 0){
      this.setData({ songs: filtered })
      wx.showToast({ title: `找到${filtered.length}首本地歌曲`, icon: 'none' })
    }
  },
  searchOnline(keyword){
    wx.showLoading({ title: '搜索音乐' })
    apiSearch(keyword).then(mapped=>{
      if(Array.isArray(mapped) && mapped.length){
        this.setData({ songs: mapped })
        wx.showToast({ title: `找到${mapped.length}首歌曲`, icon: 'success' })
      } else {
        wx.showToast({ title: '搜索无结果', icon: 'none' })
      }
    }).finally(()=> wx.hideLoading())
  },
  onMore(){ 
    wx.navigateTo({ 
      url: '/pages/ranking/ranking'
    })
  },
  playOne(e){
    const id = e.currentTarget.dataset.id
    const song = this.data.songs.find(s=>s.id===id)
    if(!song){ return }
    if(this.data.current.id===id && this.data.playing){
      audio.pause(); this.setData({ playing:false }); return
    }
    audio.title = song.name
    audio.epname = '推荐歌曲'
    audio.singer = song.artist
    audio.coverImgUrl = song.cover
    audio.src = song.url
    this.setData({ current: song, playing: true })
    this.addHistory(song)
  },
  togglePlay(){ this.data.playing ? audio.pause() : audio.play() },
  next(){
    const { songs, current } = this.data
    const idx = Math.max(0, songs.findIndex(s=>s.id===current.id))
    const next = songs[(idx+1)%songs.length]
    this.setData({ current: {} }, ()=>{ this.playByObj(next) })
  },
  playByObj(song){
    if(!song){ return }
    audio.title = song.name
    audio.singer = song.artist
    audio.coverImgUrl = song.cover
    audio.src = song.url
    this.setData({ current: song, playing: true })
    this.addHistory(song)
  },
  bindAudioEvents(){
    audio.onPlay(()=> this.setData({ playing:true }))
    audio.onPause(()=> this.setData({ playing:false }))
    audio.onStop(()=> this.setData({ playing:false, progress:0 }))
    audio.onEnded(()=> this.next())
    audio.onTimeUpdate(()=>{
      try{ this.setData({ progress: audio.currentTime / audio.duration }) }catch(e){}
    })
  },
  addHistory(song){
    const list = wx.getStorageSync('playHistory') || []
    const filtered = list.filter(i=> i.id !== song.id)
    filtered.unshift({ id: song.id, name: song.name, artist: song.artist, cover: song.cover, ts: Date.now() })
    wx.setStorageSync('playHistory', filtered.slice(0,50))
    // 同步到后端（不影响本地）
    apiHistoryAdd({ id: song.id, name: song.name, artist: song.artist, cover: song.cover }).catch(()=>{})
  },
  goToArtist(e){
    const artist = e.currentTarget.dataset.artist
    wx.navigateTo({
      url: `/pages/artist/artist?name=${encodeURIComponent(artist)}`
    })
  },
  

})
